<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'banners';
	protected $_ci;
	public function __construct()
	{
		parent::__construct();

		// Load all the required classes
		$this->load->library('form_validation');
		$this->_ci = &get_instance();
		$this->load->model('escort_ads_zones_m');
		$this->load->model('escort_ads_banners_m');
		$this->load->model('escort_ads_banner_display_geolocations_m');
		$this->load->model('escort_ads_banner_statistics_m');
		
		$this->lang->load('banner');
		$this->lang->load('zone');
		
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'ads_zone_id',
				'label' => 'lang:escort_ads_zone_zone_label',
				'rules' => 'trim|required'
			),
			array(
				'field'	=> 'site_ids',
				'label'	=> 'lang:escort_ads_zone_domain_label'
			),
			array(
				'field'	=> 'country',
				'label'	=> 'lang:escort_banner_country_label'
			),
			array(
				'field'	=> 'region',
				'label'	=> 'lang:escort_banner_region_label'
			),
			array(
				'field' => 'banner_type',
				'label'	=> 'lang:escort_banner_banner_type_label',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'image',
				'label'	=> 'lang:escort_banner_image_label',
			),
			array(
				'field' => 'display_after_login',
				'label'	=> 'lang:escort_banner_display_after_login_label',
			),
			array(
				'field' => 'define_text',
				'label' => 'lang:escort_banner_define_text_label',
				'rules' => 'trim'
			),
			array(
				'field' => 'title',
				'label' => 'lang:escort_banner_title_label',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'follow',
				'label' => 'lang:escort_banner_follow_label'
			),
			array(
				'field' => 'link',
				'label' => 'lang:escort_banner_link_label',
				'rules' => 'trim|required' 
			),
			array(
				'field' => 'script',
				'label' => 'lang:escort_banner_type_script'
			),
			array(
				'field' => 'active',
				'label' => 'lang:escort_banner_active_label'
			),
			array(
				'field' => 'code',
				'label' => 'lang:escort_banner_code_label'
			),
			array(
				'field' => 'width',
				'label' => 'lang:escort_banner_width_label'
			),
			array(
				'field' => 'height',
				'label' => 'lang:escort_banner_height_label'
			)
		);
		
		$this->data->sites = array();
		$siteEntity = new CI_Site_entity();
		if ($sites = $siteEntity->getSiteList())
		{
			foreach ($sites as $site)
			{
				$this->data->sites[$site->id] = $site->domain;
			}
		}
		
		$this->data->adsZones = array();
		$adsZoneList = $this->escort_ads_zones_m->get_all();
		if($adsZoneList){
			foreach($adsZoneList as $adsZone){
				$this->data->adsZones[$adsZone->id] = $adsZone->zone;
			}
		}
		$this->data->typeList = array(
					"text" 	=> lang('escort_banner_type_text'),
					"image"	=> lang('escort_banner_type_image'),
					"script"	=> lang('escort_banner_type_script')
		);
		
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('escort.banner.js', 'banner'))
						->append_metadata(js('jquery.simplemodal.js', 'banner'))
						->append_metadata(css('escort.banner.css', 'banner'))
						->append_metadata(css('confirm.css', 'banner'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		//set the base/default where clause
		$base_where = array();
	
		$base_where = $this->input->post('f_site') ? $base_where + array('site' => $this->input->post('f_site')) : $base_where;

		// Create pagination links
		$total_rows = $this->escort_ads_banners_m->count_by($base_where);
		$pagination = create_pagination('admin/banner/index', $total_rows);

		// Using this data, get the relevant results
		$banners = $this->escort_ads_banners_m->limit($pagination['limit'])->get_many_by($base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
			->title($this->module_details['name'])
			->append_metadata(js('admin/filter.js'))
			->set('pagination', $pagination)
			->set('banners', $banners);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);
		$ci = &get_instance();
		
		$this->data->bannerCountryList = null;
		if ($this->form_validation->run())
		{
			$site_ids = '';
			$siteIdsArray = $this->input->post('site_ids');
			
			foreach ($siteIdsArray as $key => $value) {
				$site_ids .= $value.',';
			}
			$site_ids = substr($site_ids,0, strlen($site_ids) - 1);
			
			$define_text = "";
			$image = "";
			$alt_image = "";
			$script = "";
			if($this->input->post('banner_type') == "text"){
				$define_text = $this->input->post('define_text'); 
			}
			
			if($this->input->post('banner_type') == "script"){
				$script = $this->input->post('script');
			}
			
			if($this->input->post('banner_type') == "image"){
				$config['upload_path'] = './uploads/default/files/banners';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['max_size']	= '10000';
				$config['max_width']  = '1024';
				$config['max_height']  = '768';
				
				$this->load->library('upload', $config);
				
				if ($this->upload->do_upload('image'))
				{
					$imageData = $this->upload->data();
					$image = $imageData['file_name'];
					$alt_image =  $this->input->post('title');
				}else{
					die("upload file error");
					$image = "";
				}
			}
			
			$id = $this->escort_ads_banners_m->insert(array(
						 'user_added' => $ci->ion_auth->get_user()->username,
						 'permission_slug' => $ci->ion_auth->get_user()->group,
						  'site_ids' => $site_ids,
						  'ads_zone_id' =>  $this->input->post('ads_zone_id'),
						  'banner_type' => $this->input->post('banner_type'),
						  'define_text' => $define_text  ,
						  'title' 		=> $this->input->post('title'),
						  'follow'    => $this->input->post('follow'),
						  'image' => $image  ,
						  'alt_image' => $alt_image,
						  'link' =>  $this->input->post('link') ,
						  'script'  => $script,
						  'display_after_login' => $this->input->post('display_after_login'),
						  'updated_time'  =>time() ,
						  'active'  => $this->input->post('active')
					));
			
			$countryList = $this->input->post('country_id');
			$regionList = $this->input->post('state_id');
			$provinceList = $this->input->post('province_id');
			$this->escort_ads_banner_display_geolocations_m->delete_by('ads_banner_id', $id);
			foreach($countryList as $key => $value){
				if($countryList[$key]){
					$country_id = $countryList[$key];
				}else{
					$country_id = 0;
				}
				if($regionList[$key]){
					$region_id = $regionList[$key];
				}else{
					$region_id = 0;
				}
				if($provinceList[$key]){
					$province_id = $provinceList[$key];
				}else{
					$province_id = 0;
				}
				
				$this->escort_ads_banner_display_geolocations_m->insert(array(
								'ads_banner_id'	=> $id,
								'country_id'	=> $country_id,
								'region_id'	=> $region_id,
								'province_id'	=> $province_id
				));
			}
			
			if ($id)
			{
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_add_banner', array($id));
				$this->session->set_flashdata('success', sprintf($this->lang->line('blog_post_add_success'), $this->input->post('title')));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('blog_post_add_error'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/banner') : redirect('admin/banner/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$banner->$field['field'] = set_value($field['field']);
			}

			if(($banner->banner_type == null) || ($banner->banner_type == '')){
				$banner->banner_type = "text";
			}

			$banner->user_added = $ci->ion_auth->get_user()->username;
		}

		$this->template
			->title($this->module_details['name'], lang('escort_banner_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->append_metadata(js('jquery/jquery.tagsinput.min.js'))
			->append_metadata(js('blog_form.js', 'blog'))
			->append_metadata(css('jquery/jquery.tagsinput.css'))
			->set('banner', $banner)
			->build('admin/form', $this->data);
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/banner');
	
		$banner = $this->escort_ads_banners_m->get($id);
	
		$this->form_validation->set_rules($this->validation_rules);
		
		$this->data->bannerCountryList = $this->escort_ads_banner_display_geolocations_m->get_many_by('ads_banner_id', $id);
		
		$ci = &get_instance();
		if ($this->form_validation->run())
		{
			$site_ids = '';
			$siteIdsArray = $this->input->post('site_ids');
			if($siteIdsArray){
				foreach ($siteIdsArray as $key => $value) {
					$site_ids .= $value.',';
				}
				$site_ids = substr($site_ids,0, strlen($site_ids) - 1);
			}
							
			$define_text = "";
			$image = "";
			$alt_image = "";
			$script = "";
			if($this->input->post('banner_type') == "text"){
				$define_text = $this->input->post('define_text');
			}
				
			if($this->input->post('banner_type') == "script"){
				$script = $this->input->post('script');
			}
				
			if($this->input->post('banner_type') == "image"){
				if(isset($_FILES['image']) && $_FILES['image']['name']){
					$config['upload_path'] = './uploads/default/files/banners';
					$config['allowed_types'] = 'gif|jpg|png';
					$config['max_size']	= '6000';
					$config['max_width']  = '1024';
					$config['max_height']  = '768';
					
					$this->load->library('upload', $config);
					
					if ($this->upload->do_upload('image'))
					{
						$config['image_library'] = 'gd2';
						$this->load->library('image_lib', $config);
						$imageData = $this->upload->data();
						$image = $imageData['file_name'];
						$alt_image =  $this->input->post('title');
						if(file_exists('./uploads/default/files/banners/'.$banner->image)){
							$imageData = $this->image_lib->explode_name($banner->image);
							unlink('./uploads/default/files/banners/'.$banner->image);
							unlink('uploads/default/files/banners/'.$imageData['name'].'_thumb'.$imageData['ext']);
						}
						
					}else{
						//print_r($this->upload);
						die("upload file error");
						$image = "";
					}
				}else{
					$image = $banner->image;
				}
			}
			$result = $this->escort_ads_banners_m->update($id, array(
					'user_added' => $ci->ion_auth->get_user()->username,
					 'permission_slug' => $ci->ion_auth->get_user()->group,
					  'site_ids' => $site_ids,
					  'ads_zone_id' =>  $this->input->post('ads_zone_id'),
					  'banner_type' => $this->input->post('banner_type'),
					  'define_text' => $define_text  ,
					  'title' 		=> $this->input->post('title'),
					  'follow'    => $this->input->post('follow'),
					  'image' => $image  ,
					  'alt_image' => $alt_image,
					  'link' =>  $this->input->post('link') ,
					  'script'  => $script,
					  'display_after_login' => $this->input->post('display_after_login'),
					  'updated_time'  =>time() ,
					  'active'  => $this->input->post('active')
			));
			
			$countryList = $this->input->post('country_id');
			$regionList = $this->input->post('state_id');
			$provinceList = $this->input->post('province_id');
			//print_r($provinceList);
			//die();
			$this->escort_ads_banner_display_geolocations_m->delete_by('ads_banner_id', $id);
			foreach($countryList as $key => $value){
				if($countryList[$key]){
					$country_id = $countryList[$key];
				}else{
					$country_id = 0;
				}
				if($regionList[$key]){
					$region_id = $regionList[$key];
				}else{
					$region_id = 0;
				}
				if($provinceList[$key]){
					$province_id = $provinceList[$key];
				}else{
					$province_id = 0;
				}
			
				$this->escort_ads_banner_display_geolocations_m->insert(array(
											'ads_banner_id'	=> $id,
											'country_id'	=> $country_id,
											'region_id'	=> $region_id,
											'province_id'	=> $province_id
				));
			}
			
			if ($result)
			{
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_edit_banner', array($id));
				$this->session->set_flashdata(array('success' => sprintf(lang('escort_banner_edit_success'), $this->input->post('title'))));
			}
				
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_banner_edit_error'));
			}
	
			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/banner') : redirect('admin/banner/edit/' . $id);
		}
	
		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$banner->$field['field'] = set_value($field['field']);
			}
		}
		if($banner->banner_type==''){
			$banner->banner_type = "text";
		}
		if($banner->ads_zone_id){
			$adsZone = $this->escort_ads_zones_m->get_by('id', $banner->ads_zone_id);
		}else{
			$adsZone = null;
		}
		
		$this->template
		->title($this->module_details['name'], sprintf(lang('escort_banner_edit_title'), $banner->title))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('banner', $banner)
		->set('adsZone', $adsZone)
		->build('admin/form', $this->data);
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');
	
		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$banner_titles = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($banner = $this->escort_ads_banners_m->get($id))
				{
					$this->escort_ads_banners_m->delete($id);
					do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_delete_banner', array($id));
					// Wipe cache for this model, the content has changed
					$this->pyrocache->delete('escort_ads_banners_m');
					$banner_titles[] = $banner->title;
				}
			}
		}
	
		// Some pages have been deleted
		if ( ! empty($banner_titles))
		{
			// Only deleting one page
			if (count($banner_titles) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_banner_delete_success'), $banner_titles[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_ads_banners_mass_delete_success'), implode('", "', $banner_titles)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_banner_delete_error'));
		}
	
		redirect('admin/banner');
	}
	
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/banner');
			break;
		}
	}
	
	public function statistic($id){
		$total_rows = $this->escort_ads_banner_statistics_m->where('ads_banner_id', $id)->count_all();
		$pagination = create_pagination('admin/banner/statistic/'.$id, $total_rows);
		//$statisticList = $this->escort_ads_banner_statistics_m->where('ads_banner_id', $id)->limit($pagination['limit'])->get_all();
		$statisticList = $this->escort_ads_banner_statistics_m->where('ads_banner_id', $id)->get_all();
		$this->template->set_layout(FALSE);
		$this->template
		//->set('pagination', $pagination)
		->set('statisticList', $statisticList)
		->build('admin/statistic', $this->data);
		
	}
	function get_ads_zone(){
		$adsZoneId = $this->input->post('ads_zone_id');
		$adsZone = $this->escort_ads_zones_m->get_by('id', $adsZoneId);
		$siteIds = $adsZone->site_ids;
		
		$siteIdsArray = array();
		if(strpos($siteIds, ',')){
			$tok = strtok($siteIds, ",");
			while ($tok !== false) {
				$siteIdsArray[] = $tok;
				$tok = strtok(",");
			}
		}else{
			$siteIdsArray[] = $siteIds;
		}
		$domainList = '';
		$ci = & get_instance();
		foreach($siteIdsArray as $key => $val){
			$site = $ci->site_entity->init('id',$val);
			$domainList .='<input name="site_ids[]" type="checkbox" checked="checked" value="'.$site->id.'"/><label>'.$site->domain.'</label>';
		}
		
		$result = array();
		$result['code'] = $adsZone->code;
		$result['width'] = $adsZone->width;
		$result['height'] = $adsZone->height;
		$result['domains'] = $domainList;
		
		echo json_encode($result);
	}
	public function get_state_data(){
		$country_id = $this->input->post('country_id');
	
		$ci = &get_instance();
		$current_dbprefix = $ci->db->dbprefix;
		$ci->db->set_dbprefix('default_');
	
		$COUNTRY = $ci->countries_entity->init('id',$country_id);
		$ci->db->set_dbprefix($current_dbprefix);
		$result = array();
		if($COUNTRY->getCountryCode() == 'ES'){
			$result['spain'] = true;
		}else{
			$result['spain'] = false;
		}
	
		$stateList = getStateData_ioc($country_id);
		$optionList = '<option value="0">'.lang('escort_banner_all_label').'</option>';
		if($stateList){
			foreach ($stateList as $key =>$value){
				$optionList .= 	'<option value="'.$key.'">'.$value.'</option>';
			}
		}
		$result['data'] = $optionList;
		echo json_encode($result);
	}
	
	public function get_city_data(){
		$country_id = $this->input->post('country_id');
		$state_id = $this->input->post('state_id');
		$result = array();
		$optionList = '<option value="0">'.lang("escort_banner_all_label").'</option>';	
		if($state_id == '0'){
			$result['spain'] = false;
			$result['data'] = $optionList;
			echo json_encode($result);
			return;
		}
		$ci = &get_instance();
		$current_dbprefix = $ci->db->dbprefix;
		$ci->db->set_dbprefix('default_');
		
		$COUNTRY = $ci->countries_entity->init('id',$country_id);
		$ci->db->set_dbprefix($current_dbprefix);
		
		if($COUNTRY->getCountryCode() == 'ES'){
			$cityList = getProvinceData_ioc($country_id, $state_id);
			$result['spain'] = true;
			$optionList = '<option value="0">'.lang("escort_banner_all_label").'</option>';	
		}else{
			$result['spain'] = false;
			$cityList = getCityData_ioc($country_id, $state_id, 0);
			$optionList = '<option value="0">'.lang("escort_banner_all_label").'</option>';	
		}

		
		if($cityList){
			foreach ($cityList as $key =>$value){
				$optionList .= 	'<option value="'.$key.'">'.$value.'</option>';
			}
		}
		$result['data'] = $optionList; 
		echo json_encode($result);
	}
	
	public function add_more_zone(){
		$index = $this->input->post('index');
		$data = '<li class="even multi-column">'
		.'	<ul>'
		.'		<li>'
		.'		<label for="country_id">'.lang('escort_banner_country_label').'</label>'
		.'			<div class="input">'
		.'			<select name="country_id['.$index.']" id="country_'.$index.'" class="country_select">'
		.'				<option value="0">'.lang('escort_banner_all_label').'</option>';
		$countryList = getCountryData_ioc();
		foreach ($countryList as $key => $value){
			$data .= '<option value="'.$key.'">'.$value.'</option>';
		}
		$data.=  '</select>'
		.'			</div>'
		.'		</li>'
		.'		<li>'
		.'			<label for="state_id">'.lang('escort_banner_region_label').'</label>'
		.'			<div class="input">'
		.'				<select name="state_id['.$index.']" id="state_country_'.$index.'" class="state_select">'
		.'					<option value="0">'.lang('escort_banner_all_label').'</option>'
		.'				</select>'
		.'			</div>'
		.'		</li>'
		.'		<li id="province_state_country_'.$index.'_wrapper">'
		.'			<label for="state_id">'.lang('escort_banner_province_label').'</label>'
		.'			<div class="input">'
		.'				<select name="province_id['.$index.']" id="province_state_country_'.$index.'" class="province_state_select">'
		.'					<option value="0">'.lang('escort_banner_all_label').'</option>'
		.'				</select>'
		.'			</div>'
		.'		</li>'
		.'		<li class="delete-domain">'
		.'			'.anchor('#', lang('global:delete'), array('class'=>'btn red delete', 'onclick' => 'return deleteDomain(this)')).''
		.'		</li>'
		.'	</ul>'
		.'</li>';
		echo $data;
	}
}
